console.log("test2.js");

{
    const execute = true;
    // const execute = false;
    console.log("代码块1 ,execute:",execute);
    if(execute){
        const fetchData = () => {
            return new Promise((resolve,reject)=>{
                const timeout = 500;
                // const timeout = 2000;
                // 异步操作成功
                setTimeout(()=>{
                    //
                    // const data = "data fetched";
                    const data = {id:"10"};

                    // 正常执行传递参数
                    // resolve(data);
                    // 异常执行传递参数
                    reject(data);
                },timeout);
                // 异步操作失败
            });
        }

        fetchData().then((data)=>{
            // 这边回调方法
            console.log("then data:",data);
        }).catch((e)=>{
            // 执行异常的时候，执行的方法
            console.log("catch() e,",e);
        }).finally(()=>{
            console.log("finally()")
        });

    }
}

// 代码块2
{
    const execute = true;
    // const execute = false;
    console.log("代码块2 ,execute:",execute);
    if(execute){
        function isValidUsername (str) {
            return ['admin', 'editor'].indexOf(str.trim()) >= 0;
        }
        console.log(isValidUsername("admin"));
        console.log(isValidUsername("editor"));
        console.log(isValidUsername(" editor "));
        console.log(isValidUsername(" edi tor "));
        console.log(isValidUsername("admin editor"));
    }
}

// 代码块3
{
    const execute = true;
    // const execute = false;
    console.log("代码块3 ,execute:",execute);
    if(execute){
        function isExternal (path) {
            return /^(https?:|mailto:|tel:)/.test(path);
        }
        console.log(isExternal("https://ss34"));
        console.log(isExternal("tel://10086"));
    }
}

// 代码块4
{
    const execute = true;
    // const execute = false;
    console.log("代码块4 ,execute:",execute);
    if(execute){
        // 定义一个方法句柄
        const errFun = error => {
            console.log("error",error);
        };
        errFun('ax');
    }
}

// 代码块5
{
    const execute = true;
    // const execute = false;
    console.log("代码块5 ,execute:",execute);
    if(execute){
        function parseUrl(url) {
            // 找到url中的第一个?号
            // 分别定义多个变量
            const parse = url.substring(url.indexOf("?") + 1),
                params = parse.split("&"),
                len = params.length;
            let
                item = [],
                param = {};

            for (let i = 0; i < len; i++) {
                item = params[i].split("=");
                param[item[0]] = item[1];
            }

            return param;
        }

        const result = parseUrl("http://localhost:8080?id=123&name=John&age=25");
        console.log(JSON.stringify(result));

    }
}